<?php

namespace App\Services;

use App\Models\UploadFile;
use App\Services\ImgcompressService;
use Illuminate\Support\Facades\Log;

class UploadService
{
    /**
     * 文件上传
     *
     * @param int $sizeLimit
     * @param int $riginalName
     *
     * @return mixed
     */
    public static function upload($sizeLimit = 0, $riginalName = 0)
    {
        $return['status'] = false;
        $file = isset($_FILES['file']) ? $_FILES['file'] : [];
        if ($file && $file['error'] == 0) {
            $pathinfoInfo = pathinfo($file['name']);
            $filename = $file['name'];
            $filesize = filesize($file['tmp_name']); // 单位：byte
            if (!isset($pathinfoInfo['extension']) && in_array(strtolower($pathinfoInfo['extension']), array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                $return['message'] = '格式错误，请上传png,jpeg,jpg等格式的图片';
                return $return;
            }
            if ($sizeLimit == 0 && $file['size'] >= 5 * 1024 * 1024) {
                $return['message'] = '请上传小于2M的图片';
                return $return;
            }
            $dstImg = '';
            //图片小于200kb
            if (($filesize / 1024) <= 200) {
                $fileObj = $riginalName == 0 ? createNo() . '.' . $pathinfoInfo['extension'] : $file['name'];
                $filePath = $file['tmp_name'];
            }else {
                //大于200kb需要压缩
                $dstImg = storage_path('/tmp/' . $file['name']);
                $source = $file['tmp_name'];//原图片
                $percent = 1;  #原图压缩，不缩放，但体积大大降低
                (new ImgcompressService($source, $percent))->compressImg($dstImg);
                $fileObj = $riginalName == 0 ? createNo() . '.' . $pathinfoInfo['extension'] : $file['name'];
                $filePath = $dstImg;
            }
            $resust = AlipayService::upload($fileObj, $filePath);
            if ($resust['status']) {
                if (file_exists($dstImg)) {
                    unlink($dstImg);
                }
                $return['status'] = true;
                $return['message'] = $resust['message'];
                $return['image'] = $resust['data'];
                $return['filename'] = $filename;
                $return['type'] = $file['type'];
                $return['size'] = $filesize;
                $return['info'] = $resust['info'];
                return $return;
            }
        }
        $return['message'] = '上传失败';
        return $return;
    }


    protected function getFileThumb(): string
    {
        $file_type = $this->upload_file->file_type;
        if ($file_type === UploadFile::FILE_TYPE_IMAGE) {
            //图片缩略图
            return $this->upload_file->file_url;
        }
        if ($file_type === UploadFile::FILE_TYPE_VIDEO) {
            //视频文件缩略图
            return '/assets/img/upload/video.png';
        }
        if ($file_type === UploadFile::FILE_TYPE_DOC) {
            //文档文件，根据文档后缀决定缩略图
            $array = [
                'pdf' => 'pdf.png',
                'ppt' => 'ppt.png',
                'pptx' => 'ppt.png',
                'doc' => 'doc.png',
                'docx' => 'doc.png',
                'xls' => 'xls.png',
                'xlsx' => 'xls.png',
                'file' => 'file.png',
                'video' => 'video.png'
            ];

            return '/assets/img/upload/' . ($array[$this->upload_file->file_ext] ?? 'file.png');
        }

        return '';
    }

    /**
     * 获取存储的目录
     *
     * @return string
     */
    protected function getPathDir(): string
    {
        $path_dir = '';
        $upload_file_dir = $this->config['upload_file_dir'] ?? '';
        if ($upload_file_dir != '/' && $upload_file_dir !== '') {
            $path_dir .= $upload_file_dir . DIRECTORY_SEPARATOR;
        }
        $path_dir .= $this->upload_file->file_type . DIRECTORY_SEPARATOR . date('Ym');

        return $path_dir;
    }

    function getObjectUrl($file_url): string
    {
        if (strpos($file_url, 'http') === 0) {
            return $file_url;
        } else {
            //不是http开头，拼接访问路径
            return $this->getDomain() . $file_url;
        }
    }

    function getObjectThumb(UploadFile $upload_file, $file_thumb): string
    {
        if (strpos($file_thumb, 'http') === 0) {
            return $file_thumb;
        } else {
            //不是http开头，拼接访问路径
            return $this->getDomain() . $file_thumb;
        }
    }

    /**
     * 获取域名
     *
     * @return string
     */
    private function getDomain(): string
    {
        $domain = getScheme() . "://" . $this->request->getUri()
                ->getHost();

        $port = $this->request->getUri()
            ->getPort();
        if ($port != '' && ($port != '80' || $port != '443')) {
            $domain .= ':' . $this->request->getUri()
                    ->getPort();
        }

        return $domain;
    }


}
